<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="在Python世界中游刃有余：如何灵活运用Django日志记录功能, 未央之域">
    <meta name="description" content="本文将介绍如何在Django中使用日志记录功能，以及如何使用Django自带的日志记录功能。">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="referrer" content="no-referrer-when-downgrade">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>在Python世界中游刃有余：如何灵活运用Django日志记录功能 | 未央之域</title>
    <link rel="icon" type="image/png" href="/medias/favicon.png">
    


    <!-- bg-cover style     -->



<link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.min.css">
<link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
<link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
<link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
<link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
<link rel="stylesheet" type="text/css" href="/css/matery.css">
<link rel="stylesheet" type="text/css" href="/css/my.css">
<link rel="stylesheet" type="text/css" href="/css/dark.css" media="none" onload="if(media!='all')media='all'">




    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
    <link rel="stylesheet" href="/css/post.css">




    



    <script src="/libs/jquery/jquery-3.6.0.min.js"></script>

<meta name="generator" content="Hexo 6.3.0"><link rel="alternate" href="/atom.xml" title="未央之域" type="application/atom+xml">
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>


<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">未央之域</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
  <li>
    <a href="javascript:;" class="waves-effect waves-light" onclick="switchNightMode()" title="深色/浅色模式" >
      <i id="sum-moon-icon" class="fas fa-sun" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">未央之域</div>
        <div class="logo-desc">
            
            Never really desperate, only the lost of the soul.
            
        </div>
    </div>

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/wxs0088" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/wxs0088" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('https://www.sentinelone.com/wp-content/uploads/2022/02/Django_logging_with_Scalyr_colors.png')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">在Python世界中游刃有余：如何灵活运用Django日志记录功能</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/Python/">
                                <span class="chip bg-color">Python</span>
                            </a>
                        
                            <a href="/tags/Django/">
                                <span class="chip bg-color">Django</span>
                            </a>
                        
                            <a href="/tags/%E6%97%A5%E5%BF%97%E8%AE%B0%E5%BD%95/">
                                <span class="chip bg-color">日志记录</span>
                            </a>
                        
                            <a href="/tags/Logging/">
                                <span class="chip bg-color">Logging</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/Django/" class="post-category">
                                Django
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2023-04-24
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2023-04-24
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    2.8k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    10 分
                </div>
                

                
            </div>
        </div>
        <hr class="clearfix">

        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h3 id="一、写在前面"><a href="#一、写在前面" class="headerlink" title="一、写在前面"></a>一、写在前面</h3><p>Django 是一个流行的 Python Web 框架，并且在开发过程中，日志记录是很重要的一部分。随着应用程序变得越来越复杂，我们不可避免地需要更细致、更高级的调试和追踪工具。<br>在Django的世界里，logging（日志记录）成了一个非常重要并且强大的工具。它可以帮助我们记录所有应用程序运行过程中的事件，从而让开发者能够更好地理解应用程序以及其中代码的工作方式。</p>
<p>那么，在Django中如何使用logging来分析我们的代码运行时出现的问题呢？接下来，我将会向您介绍如何利用Django 4.1.7<br>中的logging来提高开发质量和效率。</p>
<h3 id="二、什么是-logging"><a href="#二、什么是-logging" class="headerlink" title="二、什么是 logging"></a>二、什么是 logging</h3><p>logging到底是什么：简单地说，logging就是一种把程序运行时的信息（调试信息、错误、警告等）输出到指定位置的技术。当应用程序崩溃或者在运行上出现其他问题时，这些信息就会被日志记录器捕获，并显示给开发者来分析和理解问题原因。</p>
<p>logging日志还可以在开发者的控制台、文件甚至是邮件中显示，从而让开发者快速地了解应用程序的运行情况。</p>
<h3 id="三、Django中的logging"><a href="#三、Django中的logging" class="headerlink" title="三、Django中的logging"></a>三、Django中的logging</h3><p>Django提供了一组可定制的日志记录方式，以便开发者能够追踪他们的应用程序从框架到应用程序本身所打印的日志记录。Django提供的logging配置会输出所有的错误、警告和信息消息。如果你想在调试过程中获取更详细的数据，那么logging就是您非常重要的一个工具。</p>
<ol>
<li><p>Django日志记录器的默认配置：</p>
<p>根日志级别 (Root Logger Level)：WARNING<br>在指定文件中保存（Rotate）日志<br>固定格式，包含日期时间戳、日志分类、模块名称和日志等级<br>这里是一个简单的例子，演示如何启用日志系统并记录一些信息。</p>
<pre class=" language-python"><code class="language-python"><span class="token keyword">import</span> logging

logger <span class="token operator">=</span> logging<span class="token punctuation">.</span>getLogger<span class="token punctuation">(</span>__name__<span class="token punctuation">)</span>

<span class="token keyword">def</span> <span class="token function">my_view</span><span class="token punctuation">(</span>request<span class="token punctuation">,</span> arg1<span class="token punctuation">,</span> arg<span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token comment" spellcheck="true"># do something interesting </span>
    logger<span class="token punctuation">.</span>info<span class="token punctuation">(</span><span class="token string">'Receiving request from %s'</span><span class="token punctuation">,</span> request<span class="token punctuation">)</span>
    <span class="token keyword">try</span><span class="token punctuation">:</span>
        result <span class="token operator">=</span> some_function<span class="token punctuation">(</span>arg1<span class="token punctuation">,</span> arg2<span class="token punctuation">)</span>
    <span class="token keyword">except</span> Exception<span class="token punctuation">:</span>
        logger<span class="token punctuation">.</span>exception<span class="token punctuation">(</span><span class="token string">"Error when calling some_function()"</span><span class="token punctuation">)</span>
    <span class="token keyword">return</span> HttpResponse<span class="token punctuation">(</span>result<span class="token punctuation">)</span>
</code></pre>
<p>上面的例子顺序地展示了创建一个日志记录器实例 logger &#x3D; logging.getLogger(<strong>name</strong>) 。 然后，在 my_view 函数中使用它来记录信息。</p>
<p>其中，通过例子可以看出 logging 模块结合 Django 包含以下几部分：</p>
<p>Module 信息<br>日志记录级别<br>日志分发处理器<br>格式化信息<br>过滤器<br>Python标准库中的logging模块提供了一个灵活的机制，允许开发人员自定义筛选日志事件以及将其路由到目标位置的方法。这允许开发者采取不同的方式来处理应用程序的多个日志消息类型并按需修改配置。</p>
</li>
<li><p>日志输出等级（Log Levels）</p>
<p>在logging系统中，存在5种默认记录级别，列举如下：</p>
<ol>
<li>DEBUG：详细的日志记录，通常只出现在诊断问题上</li>
<li>INFO：证明事情按预期工作</li>
<li>WARNING：指示可能出了问题，但直接影响程序正常运行的级别</li>
<li>ERROR：由于更严重的问题，该软件无法执行某些功能</li>
<li>CRITICAL：指出非常严重的错误，表明程序本身可能无法继续进行<br>通过 logging 模块的 setLevel 来确定记录的等级。如果您将记录器级别设置为 DEBUG，则所有可用级别的日志记录都可以被记录。如果您将其设置为<br>ERROR，则所有 ERROR 和 CRITICAL 级别的日志将被记录，但其他等级的日志则不会被处理。</li>
</ol>
</li>
<li><p>日志输出格式</p>
<p>另一个重要的logging配置是日志记录格式。Django使用string format语法的logging.basicConfig()方法，可以很容易地自定义输出的日志信息。</p>
<p>格式化字符串中，可以使用以下一些占位符：</p>
<ol>
<li>%(asctime)s：日志记录的时间</li>
<li>%(levelname)s：日志记录的级别</li>
<li>%(name)s：日志记录器的名称</li>
<li>%(message)s：日志记录的消息</li>
<li>%(filename)s：产生日志记录的文件名</li>
<li>%(module)s：产生日志记录的模块名</li>
<li>%(funcName)s：产生日志记录的函数名</li>
<li>%(lineno)d：产生日志记录的代码行号</li>
<li>%(process)d：进程ID</li>
<li>%(thread)d：线程ID</li>
<li>%(threadName)s：线程名称</li>
<li>%(pathname)s：产生日志记录的代码文件的完整路径名</li>
<li>%(processName)s：进程名称<br>下面是一个例子显示了如何设置自己的格式化。</li>
</ol>
<pre class=" language-python"><code class="language-python"><span class="token string">'formatters'</span><span class="token punctuation">:</span> <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#123;</span>
    <span class="token string">'verbose'</span><span class="token punctuation">:</span> <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#123;</span>
        <span class="token string">'format'</span><span class="token punctuation">:</span> <span class="token string">'%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'</span>
    <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#125;,</span>

    <span class="token string">'simple'</span><span class="token punctuation">:</span> <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#123;</span>
        <span class="token string">'format'</span><span class="token punctuation">:</span> <span class="token string">'%(levelname)s %(message)s'</span>
    <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#125;,</span>

    <span class="token comment" spellcheck="true"># 标准输出格式</span>
    <span class="token string">'standard'</span><span class="token punctuation">:</span> <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#123;</span>
        <span class="token comment" spellcheck="true"># (日志级别ID) [具体时间][线程名:线程ID][日志名字:])] [输出的模块:输出的函数]:日志内容</span>
        <span class="token string">'format'</span><span class="token punctuation">:</span> <span class="token string">'%(levelname)s [%(asctime)s] %(process)d %(thread)d "%(pathname)s/%(funcName)s:%(lineno)d" %(message)s'</span><span class="token punctuation">,</span>
        <span class="token string">'datefmt'</span><span class="token punctuation">:</span> <span class="token string">'%d/%b/%Y:%H:%M:%S %z'</span><span class="token punctuation">,</span>
        <span class="token comment" spellcheck="true"># 23/Dec/2017:14:21:40 +0800</span>
    <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#125;,</span>
<span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#125;</span>
</code></pre>
<p>其中， LOGGING 中定义了根记录器的配置。 它表示Django默认情况下为我们安装和配置的 logging系统。<br>我们通过继承默认的配置并对其进行修改来对其进行自定义。</p>
<p>除此之外，你还可以设置其他函数来更加精确地控制日志处理。例如，您可以定义过滤器来动态更改日志级别等。</p>
<p><code>loggerFilter.py</code></p>
<pre class=" language-python"><code class="language-python"><span class="token keyword">import</span> logging
<span class="token keyword">class</span> <span class="token class-name">UrlFilter</span><span class="token punctuation">(</span>logging<span class="token punctuation">.</span>Filter<span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">def</span> <span class="token function">filter</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> record<span class="token punctuation">)</span><span class="token punctuation">:</span>
        urls_to_ignore <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">'/api/template/get_software/'</span><span class="token punctuation">,</span> <span class="token string">'/api/software/software_install_status/'</span><span class="token punctuation">]</span>
        <span class="token keyword">for</span> url <span class="token keyword">in</span> urls_to_ignore<span class="token punctuation">:</span>
            <span class="token keyword">if</span> record<span class="token punctuation">.</span>getMessage<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span>startswith<span class="token punctuation">(</span><span class="token string">'"POST &amp;#123;&amp;#125;'</span><span class="token punctuation">.</span>format<span class="token punctuation">(</span>url<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
                <span class="token keyword">return</span> <span class="token boolean">False</span>
        <span class="token keyword">return</span> <span class="token boolean">True</span>
</code></pre>
<p><code>settings.py</code></p>
<pre class=" language-python"><code class="language-python"><span class="token keyword">from</span> loggerFilter <span class="token keyword">import</span> <span class="token operator">*</span>
<span class="token string">'filters'</span><span class="token punctuation">:</span> <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#123;</span>
    <span class="token comment" spellcheck="true"># 只有在Django debug为True时才在屏幕打印日志</span>
    <span class="token string">'require_debug_true'</span><span class="token punctuation">:</span> <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#123;</span>
        <span class="token string">'()'</span><span class="token punctuation">:</span> <span class="token string">'django.utils.log.RequireDebugTrue'</span><span class="token punctuation">,</span>
    <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#125;,</span>
    <span class="token comment" spellcheck="true"># 过滤url</span>
    <span class="token string">'url_filter'</span><span class="token punctuation">:</span> <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#123;</span>
        <span class="token string">'()'</span><span class="token punctuation">:</span> UrlFilter<span class="token punctuation">,</span>
    <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#125;,</span>
<span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#125;</span>
</code></pre>
</li>
<li><p>日志分发处理器</p>
<p>logging模块提供了多种处理器，用于将日志消息发送到不同的目的地。Django默认配置中的处理器有：</p>
<ol>
<li>NullHandler：不做任何处理</li>
<li>StreamHandler：将日志消息发送到输出流，如sys.stderr, sys.stdout或任何文件-like对象</li>
<li>FileHandler：将日志消息发送到磁盘文件，默认情况下文件大小会无限增长</li>
<li>SMTPHandler：将日志消息以电子邮件的形式发送给管理员</li>
<li>HTTPHandler：将日志消息以GET或POST的形式发送到一个HTTP服务器</li>
<li>BaseRotatingHandler：基类，用于将日志消息发送到磁盘文件，并支持日志文件的自动切割</li>
<li>RotatingFileHandler：继承自BaseRotatingHandler，用于将日志消息发送到磁盘文件，并支持日志文件的自动切割</li>
<li>TimedRotatingFileHandler：继承自BaseRotatingHandler，用于将日志消息发送到磁盘文件，并支持日志文件的按时间自动切割</li>
<li>SocketHandler：将日志消息发送到网络套接字</li>
<li>DatagramHandler：将日志消息发送到网络套接字，但使用UDP协议</li>
<li>SysLogHandler：将日志消息发送到UNIX系统的syslogd守护进程</li>
<li>NTEventLogHandler：将日志消息发送到Windows NT&#x2F;2000&#x2F;XP的事件日志</li>
<li>MemoryHandler：将日志消息发送到内存中的制定buffer</li>
<li>HTTPHandler：将日志消息以GET或POST的形式发送到一个HTTP服务器</li>
<li>QueueHandler：将日志消息发送到multiprocessing.Queue对象</li>
<li>QueueListener：从multiprocessing.Queue对象中读取消息，并将这些消息发送到指定的处理器</li>
</ol>
<p>除了上面列出的处理器，Django还提供了一些自定义的处理器，用于将日志消息发送到不同的目的地。Django默认配置中的处理器有：</p>
<ol>
<li>AdminEmailHandler：将日志消息以电子邮件的形式发送给管理员</li>
<li>ColorizingStreamHandler：将日志消息发送到输出流，如sys.stderr, sys.stdout或任何文件-like对象，并且可以为不同的日志级别设置不同的颜色</li>
<li>SafeExceptionReporterFilter：过滤掉敏感信息，如数据库密码等</li>
<li>ServerFormatter：格式化日志消息，用于将日志消息发送到远程服务器</li>
<li>SMTPFormatter：格式化日志消息，用于将日志消息以电子邮件的形式发送给管理员</li>
<li>UnicodeStreamHandler：将日志消息发送到输出流，如sys.stderr, sys.stdout或任何文件-like对象，并且可以为不同的日志级别设置不同的颜色</li>
</ol>
<p>除了上面列出的处理器，Django还提供了一些自定义的处理器，用于将日志消息发送到不同的目的地。Django默认配置中的处理器有：</p>
<ol>
<li>AdminEmailHandler：将日志消息以电子邮件的形式发送给管理员</li>
<li>ColorizingStreamHandler：将日志消息发送到输出流，如sys.stderr, sys.stdout或任何文件-like对象，并且可以为不同的日志级别设置不同的颜色</li>
<li>SafeExceptionReporterFilter：过滤掉敏感信息，如数据库密码等</li>
</ol>
</li>
<li><p>配置示例</p>
</li>
</ol>
<pre class=" language-python"><code class="language-python">LOGGING <span class="token operator">=</span> <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#123;</span>
    <span class="token string">'version'</span><span class="token punctuation">:</span> <span class="token number">1</span><span class="token punctuation">,</span>
    <span class="token comment" spellcheck="true"># 是否启用日志配置</span>
    <span class="token string">'disable_existing_loggers'</span><span class="token punctuation">:</span> <span class="token boolean">False</span><span class="token punctuation">,</span>
    <span class="token comment" spellcheck="true"># 日志文件的配置-格式化输出</span>
    <span class="token string">'formatters'</span><span class="token punctuation">:</span> <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#123;</span>
        <span class="token string">'verbose'</span><span class="token punctuation">:</span> <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#123;</span>
            <span class="token string">'format'</span><span class="token punctuation">:</span> <span class="token string">'%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'</span>
        <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#125;,</span>

        <span class="token string">'simple'</span><span class="token punctuation">:</span> <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#123;</span>
            <span class="token string">'format'</span><span class="token punctuation">:</span> <span class="token string">'%(levelname)s %(message)s'</span>
        <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#125;,</span>

        <span class="token comment" spellcheck="true"># 标准输出格式</span>
        <span class="token string">'standard'</span><span class="token punctuation">:</span> <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#123;</span>
            <span class="token comment" spellcheck="true"># (日志级别ID) [具体时间][线程名:线程ID][日志名字:])] [输出的模块:输出的函数]:日志内容</span>
            <span class="token string">'format'</span><span class="token punctuation">:</span> <span class="token string">'%(levelname)s [%(asctime)s] %(process)d %(thread)d "%(pathname)s/%(funcName)s:%(lineno)d" %(message)s'</span><span class="token punctuation">,</span>
            <span class="token string">'datefmt'</span><span class="token punctuation">:</span> <span class="token string">'%d/%b/%Y:%H:%M:%S %z'</span><span class="token punctuation">,</span>
            <span class="token comment" spellcheck="true"># 23/Dec/2017:14:21:40 +0800</span>
        <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#125;,</span>
    <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#125;,</span>
    <span class="token comment" spellcheck="true"># 过滤器</span>
    <span class="token string">'filters'</span><span class="token punctuation">:</span> <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#123;</span>
        <span class="token comment" spellcheck="true"># 只有在Django debug为True时才在屏幕打印日志</span>
        <span class="token string">'require_debug_true'</span><span class="token punctuation">:</span> <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#123;</span>
            <span class="token string">'()'</span><span class="token punctuation">:</span> <span class="token string">'django.utils.log.RequireDebugTrue'</span><span class="token punctuation">,</span>
        <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#125;,</span>
        <span class="token comment" spellcheck="true"># 过滤url</span>
        <span class="token string">'url_filter'</span><span class="token punctuation">:</span> <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#123;</span>
            <span class="token string">'()'</span><span class="token punctuation">:</span> UrlFilter<span class="token punctuation">,</span>
        <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#125;,</span>
    <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#125;,</span>
    <span class="token comment" spellcheck="true"># 处理器</span>
    <span class="token string">'handlers'</span><span class="token punctuation">:</span> <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#123;</span>
        <span class="token comment" spellcheck="true"># 控制台输出</span>
        <span class="token string">'console'</span><span class="token punctuation">:</span> <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#123;</span>
            <span class="token string">'level'</span><span class="token punctuation">:</span> <span class="token string">'INFO'</span><span class="token punctuation">,</span>
            <span class="token string">'class'</span><span class="token punctuation">:</span> <span class="token string">'logging.StreamHandler'</span><span class="token punctuation">,</span>
            <span class="token string">'filters'</span><span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token string">'require_debug_true'</span><span class="token punctuation">,</span> <span class="token string">'url_filter'</span><span class="token punctuation">]</span><span class="token punctuation">,</span>
            <span class="token string">'formatter'</span><span class="token punctuation">:</span> <span class="token string">'simple'</span><span class="token punctuation">,</span>
        <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#125;,</span>
        <span class="token comment" spellcheck="true"># 调试信息</span>
        <span class="token string">'info_file'</span><span class="token punctuation">:</span> <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#123;</span>
            <span class="token string">'level'</span><span class="token punctuation">:</span> <span class="token string">'INFO'</span><span class="token punctuation">,</span>
            <span class="token string">'class'</span><span class="token punctuation">:</span> <span class="token string">'logging.handlers.RotatingFileHandler'</span><span class="token punctuation">,</span>
            <span class="token string">'filters'</span><span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token string">'url_filter'</span><span class="token punctuation">]</span><span class="token punctuation">,</span>
            <span class="token string">'filename'</span><span class="token punctuation">:</span> os<span class="token punctuation">.</span>path<span class="token punctuation">.</span>join<span class="token punctuation">(</span>BASE_DIR<span class="token punctuation">,</span> <span class="token string">'logs/info.log'</span><span class="token punctuation">)</span><span class="token punctuation">,</span>  <span class="token comment" spellcheck="true"># 输出位置(先创建文件夹)</span>
            <span class="token string">'formatter'</span><span class="token punctuation">:</span> <span class="token string">'standard'</span><span class="token punctuation">,</span>
            <span class="token string">'maxBytes'</span><span class="token punctuation">:</span> <span class="token number">5</span> <span class="token operator">*</span> <span class="token number">1024</span> <span class="token operator">*</span> <span class="token number">1024</span><span class="token punctuation">,</span>
            <span class="token string">'backupCount'</span><span class="token punctuation">:</span> <span class="token number">10</span>
        <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#125;,</span>
        <span class="token comment" spellcheck="true"># django日志</span>
        <span class="token string">'django_file'</span><span class="token punctuation">:</span> <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#123;</span>
            <span class="token string">'level'</span><span class="token punctuation">:</span> <span class="token string">'DEBUG'</span><span class="token punctuation">,</span>
            <span class="token string">'class'</span><span class="token punctuation">:</span> <span class="token string">'logging.handlers.RotatingFileHandler'</span><span class="token punctuation">,</span>
            <span class="token string">'filename'</span><span class="token punctuation">:</span> os<span class="token punctuation">.</span>path<span class="token punctuation">.</span>join<span class="token punctuation">(</span>BASE_DIR<span class="token punctuation">,</span> <span class="token string">'logs/django.log'</span><span class="token punctuation">)</span><span class="token punctuation">,</span>  <span class="token comment" spellcheck="true"># 输出位置(先创建文件夹)</span>
            <span class="token string">'formatter'</span><span class="token punctuation">:</span> <span class="token string">'simple'</span><span class="token punctuation">,</span>
            <span class="token string">'maxBytes'</span><span class="token punctuation">:</span> <span class="token number">5</span> <span class="token operator">*</span> <span class="token number">1024</span> <span class="token operator">*</span> <span class="token number">1024</span><span class="token punctuation">,</span>
            <span class="token string">'backupCount'</span><span class="token punctuation">:</span> <span class="token number">100</span>
        <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#125;,</span>
        <span class="token comment" spellcheck="true"># 重大错误日志</span>
        <span class="token string">'error_file'</span><span class="token punctuation">:</span> <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#123;</span>
            <span class="token string">'level'</span><span class="token punctuation">:</span> <span class="token string">'ERROR'</span><span class="token punctuation">,</span>
            <span class="token string">'class'</span><span class="token punctuation">:</span> <span class="token string">'logging.handlers.RotatingFileHandler'</span><span class="token punctuation">,</span>
            <span class="token string">'filename'</span><span class="token punctuation">:</span> os<span class="token punctuation">.</span>path<span class="token punctuation">.</span>join<span class="token punctuation">(</span>BASE_DIR<span class="token punctuation">,</span> <span class="token string">'logs/error.log'</span><span class="token punctuation">)</span><span class="token punctuation">,</span>  <span class="token comment" spellcheck="true"># 输出位置(先创建文件夹)</span>
            <span class="token string">'formatter'</span><span class="token punctuation">:</span> <span class="token string">'standard'</span><span class="token punctuation">,</span>
            <span class="token string">'maxBytes'</span><span class="token punctuation">:</span> <span class="token number">5</span> <span class="token operator">*</span> <span class="token number">1024</span> <span class="token operator">*</span> <span class="token number">1024</span><span class="token punctuation">,</span>
            <span class="token string">'backupCount'</span><span class="token punctuation">:</span> <span class="token number">10</span>
        <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#125;</span>
    <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#125;,</span>
    <span class="token comment" spellcheck="true"># 日志记录器</span>
    <span class="token string">'loggers'</span><span class="token punctuation">:</span> <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#123;</span>
        <span class="token comment" spellcheck="true"># 自定义日志</span>
        <span class="token string">''</span><span class="token punctuation">:</span> <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#123;</span>
            <span class="token string">'handlers'</span><span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token string">'info_file'</span><span class="token punctuation">,</span> <span class="token string">'console'</span><span class="token punctuation">]</span><span class="token punctuation">,</span>
            <span class="token string">'level'</span><span class="token punctuation">:</span> <span class="token string">'INFO'</span><span class="token punctuation">,</span>
            <span class="token string">'propagate'</span><span class="token punctuation">:</span> <span class="token boolean">False</span><span class="token punctuation">,</span>
        <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#125;,</span>
        <span class="token comment" spellcheck="true"># django日志</span>
        <span class="token string">'django'</span><span class="token punctuation">:</span> <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#123;</span>
            <span class="token string">'handlers'</span><span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token string">'django_file'</span><span class="token punctuation">]</span><span class="token punctuation">,</span>
            <span class="token string">'level'</span><span class="token punctuation">:</span> <span class="token string">'DEBUG'</span><span class="token punctuation">,</span>
            <span class="token string">'propagate'</span><span class="token punctuation">:</span> <span class="token boolean">True</span><span class="token punctuation">,</span>
        <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#125;,</span>
        <span class="token comment" spellcheck="true"># 错误日志</span>
        <span class="token string">'error'</span><span class="token punctuation">:</span> <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#123;</span>
            <span class="token string">'handlers'</span><span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token string">'error_file'</span><span class="token punctuation">]</span><span class="token punctuation">,</span>
            <span class="token string">'level'</span><span class="token punctuation">:</span> <span class="token string">'ERROR'</span><span class="token punctuation">,</span>
            <span class="token string">'propagate'</span><span class="token punctuation">:</span> <span class="token boolean">False</span><span class="token punctuation">,</span>
        <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#125;</span>
    <span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#125;,</span>
<span class="token operator">&amp;</span><span class="token comment" spellcheck="true">#125;</span>
</code></pre>
<h3 id="四、总结"><a href="#四、总结" class="headerlink" title="四、总结"></a>四、总结</h3><p>Django 内置的 logging 库提供了强大和灵活的日志记录功能，可以方便地满足不同的需求。本文介绍了 Django 中 logger<br>的基本配置和使用方法，希望能给读者带来一些思路。再次强调，在生产环境中日志记录很重要，因此应该专注于正确配置 logger<br>以及在应用程序中使用它来记录日志。</p>
<p>最后，提醒一下：正确地配置 logging 是必要且重要的一步，因为它直接影响实际应用程序的性能。因此，我们应该使用得当而不是滥用它。</p>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">未央</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://sirxs.cn/2023/04/24/logging/">https://sirxs.cn/2023/04/24/logging/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">未央</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/Python/">
                                    <span class="chip bg-color">Python</span>
                                </a>
                            
                                <a href="/tags/Django/">
                                    <span class="chip bg-color">Django</span>
                                </a>
                            
                                <a href="/tags/%E6%97%A5%E5%BF%97%E8%AE%B0%E5%BD%95/">
                                    <span class="chip bg-color">日志记录</span>
                                </a>
                            
                                <a href="/tags/Logging/">
                                    <span class="chip bg-color">Logging</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
        </div>
    </div>

    

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2023/04/25/ubuntu22-04-server-an-zhuang/">
                    <div class="card-image">
                        
                        <img src="https://wangxs020202.gitee.io/pbad/new/ubuntu.jpg" class="responsive-img" alt="Ubuntu 22.04 Server 安装实录：探索 Linux Server 世界的无限可能！">
                        
                        <span class="card-title">Ubuntu 22.04 Server 安装实录：探索 Linux Server 世界的无限可能！</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            记录一次Ubuntu 22.04 Server的安装实录
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2023-04-25
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Linux/" class="post-category">
                                    Linux
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Ubuntu/">
                        <span class="chip bg-color">Ubuntu</span>
                    </a>
                    
                    <a href="/tags/Linux/">
                        <span class="chip bg-color">Linux</span>
                    </a>
                    
                    <a href="/tags/Shell/">
                        <span class="chip bg-color">Shell</span>
                    </a>
                    
                    <a href="/tags/Vim/">
                        <span class="chip bg-color">Vim</span>
                    </a>
                    
                    <a href="/tags/SSH/">
                        <span class="chip bg-color">SSH</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2023/04/23/test/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/10.jpg" class="responsive-img" alt="test">
                        
                        <span class="card-title">test</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2023-04-23
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-user fa-fw"></i>
                            未央
                            
                        </span>
                    </div>
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>



<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>



    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    

    <div class="container row center-align"
         style="margin-bottom: 15px !important;">
        <div class="col s12 m8 l8 copy-right">
            <!-- 版权 -->

            Copyright&nbsp;&copy;
            
                <span id="year">2020-2023</span>
            

            <!-- _config配置的 author 可直接跳转到 about 页面
                <a href="/about" target="_blank">未央</a>
             -->
            <!-- 简繁替换 -->
            
            <br>
            <!-- 总字数 -->
            
                &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                        class="white-color">11.8k</span>
            

            
            
            <!--  总访问量 -->
            
            <!-- 总访问人数 -->
            
            <br>
            <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
            <span id="busuanzi_container_site_pv">本站总访问量<span id="busuanzi_value_site_pv"></span>次</span>

            <br>

            <!-- 运行天数提醒. -->
            
                <span id="sitetime"> Loading ...</span>
                <script>
                    var calcSiteTime = function () {
                        var seconds = 1000;
                        var minutes = seconds * 60;
                        var hours = minutes * 60;
                        var days = hours * 24;
                        var years = days * 365;
                        var today = new Date();
                        var startYear = "2020";
                        var startMonth = "6";
                        var startDate = "28";
                        var startHour = "2";
                        var startMinute = "3";
                        var startSecond = "15";
                        var todayYear = today.getFullYear();
                        var todayMonth = today.getMonth() + 1;
                        var todayDate = today.getDate();
                        var todayHour = today.getHours();
                        var todayMinute = today.getMinutes();
                        var todaySecond = today.getSeconds();
                        var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                        var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                        var diff = t2 - t1;
                        var diffYears = Math.floor(diff / years);
                        var diffDays = Math.floor((diff / days) - diffYears * 365);

                        // 区分是否有年份.
                        var language = 'zh-CN';
                        if (startYear === String(todayYear)) {
                            document.getElementById("year").innerHTML = todayYear;
                            var daysTip = 'This site has been running for ' + diffDays + ' days';
                            if (language === 'zh-CN') {
                                daysTip = '本站已运行 ' + diffDays + ' 天';
                            } else if (language === 'zh-HK') {
                                daysTip = '本站已運行 ' + diffDays + ' 天';
                            }
                            document.getElementById("sitetime").innerHTML = daysTip;
                        } else {
                            document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                            var yearsAndDaysTip = 'This site has been running for ' + diffYears + ' years and '
                                + diffDays + ' days';
                            if (language === 'zh-CN') {
                                yearsAndDaysTip = '本站已运行 ' + diffYears + ' 年 ' + diffDays + ' 天';
                            } else if (language === 'zh-HK') {
                                yearsAndDaysTip = '本站已運行 ' + diffYears + ' 年 ' + diffDays + ' 天';
                            }
                            document.getElementById("sitetime").innerHTML = yearsAndDaysTip;
                        }
                    }

                    calcSiteTime();
                </script>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link ">
    <a href="https://github.com/wxs0088" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>















    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 白天和黑夜主题 -->
<div class="stars-con">
    <div id="stars"></div>
    <div id="stars2"></div>
    <div id="stars3"></div>  
</div>

<script>
    function switchNightMode() {
        $('<div class="Cuteen_DarkSky"><div class="Cuteen_DarkPlanet"></div></div>').appendTo($('body')),
        setTimeout(function () {
            $('body').hasClass('DarkMode') 
            ? ($('body').removeClass('DarkMode'), localStorage.setItem('isDark', '0'), $('#sum-moon-icon').removeClass("fa-sun").addClass('fa-moon')) 
            : ($('body').addClass('DarkMode'), localStorage.setItem('isDark', '1'), $('#sum-moon-icon').addClass("fa-sun").removeClass('fa-moon')),
            
            setTimeout(function () {
            $('.Cuteen_DarkSky').fadeOut(1e3, function () {
                $(this).remove()
            })
            }, 2e3)
        })
    }
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    

    
    
    

    <!-- 雪花特效 -->
    

    <!-- 鼠标星星特效 -->
    

     
        <script src="https://ssl.captcha.qq.com/TCaptcha.js"></script>
        <script src="/libs/others/TencentCaptcha.js"></script>
        <button id="TencentCaptcha" data-appid="xxxxxxxxxx" data-cbfn="callback" type="button" hidden></button>
    

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    

    

    

    <!--腾讯兔小巢-->
    
    

    

    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
